<template>
  <div class="container">
    <div class="search-container">
      <div class="search-option-row" >
        <label class="search-option-label">项目名称</label>
        <div class="search-option-col">
          <el-input v-model="listQuery.project_name"  class="select-item"  placeholder="" style="width:150px"></el-input>
        </div>
        <label class="search-option-label">公司名称</label>
        <div class="search-option-col">
          <el-input v-model="listQuery.company_name"  class="select-item"  placeholder="" style="width:150px"></el-input>
        </div>
        <label class="search-option-label">状态</label>
        <div class="search-option-col">
          <el-select
            style="width:150px"
            v-model="listQuery.project_status"
            filterable
            clearable
            collapse-tags
            placeholder="请选择">
            <el-option
              v-for="item in projectStatusOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="search-option-row" >
        <label class="search-option-label">客户经理</label>
        <div class="search-option-col">
          <el-input v-model="listQuery.client_manager"  class="select-item"  placeholder="" style="width:150px"></el-input>
        </div>
        <label class="search-option-label">主要顾问</label>
        <div class="search-option-col">
          <el-input v-model="listQuery.manager_consultant"  class="select-item"  placeholder="" style="width:150px"></el-input>
        </div>
        <label class="search-option-label">城市</label>
        <div class="search-option-col">
          <treeselect
          class="select-item"
          :multiple="true"
          :options="city_options"
          :load-options="loadChildrenOptions"
          :valueConsistsOf="valueConsistsOf"
          placeholder="请选择"
          v-model="listQuery.city"
          style="width:160px"
          />
        </div>
      </div>
      <div class="search-option-row" >
        <label class="search-option-label">优先级</label>
        <div class="search-option-col">
          <el-select
            style="width:150px"
            v-model="listQuery.project_priority"
            filterable
            clearable
            collapse-tags
            placeholder="请选择">
            <el-option
              v-for="item in projectPriorityOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key">
            </el-option>
          </el-select>
        </div>
        <label class="search-option-label">行业</label>
        <div class="search-option-col">
           <treeselect
          class="select-item"
          :multiple="true"
          :load-options="loadChildrenOptions"
          :options="industry_options"
          :valueConsistsOf="valueConsistsOf"
          placeholder="请选择"
          v-model="listQuery.industry"
          style="width:200px"
          />
         </div>
        <label class="search-option-label">职能</label>
        <div class="search-option-col">
          <treeselect
          class="select-item"
          :multiple="true"
          :load-options="loadChildrenOptions"
          :options="job_options"
          :valueConsistsOf="valueConsistsOf"
          placeholder="请选择"
          v-model="listQuery.function"
          style="width:200px"
        />
        </div>
      </div>
      <div class="search-button-row">
        <label class="search-button-label"></label>
        <div class="search-button-col">
        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleFilter" round>搜索</el-button>
        <el-button size="mini" type="primary" icon="el-icon-refresh" @click="clearOptions" round>清空</el-button>
        </div>
      </div>
    </div>
    <div class="table-header-row">
      <div class="table-header-button">
          <el-button plain size="mini" @click="handleCreate" >新增项目</el-button>
          <el-button plain size="mini" v-if="hasRoles(['PROJECT_MEMBER_UPDATE', 'SUPER_ADMIN'])" :disabled="updateClientManagerDisable" @click="handleBatchUpdateClientManager">维护客户经理</el-button>
          <el-button plain size="mini" v-if="hasRoles(['PROJECT_MEMBER_UPDATE', 'SUPER_ADMIN'])" :disabled="updateManagerConsultantDisable" @click="handleBatchUpdateManagerConsultant" >维护主要顾问</el-button>
          <el-button plain size="mini" v-if="hasRoles(['PROJECT_MEMBER_UPDATE', 'SUPER_ADMIN'])" :disabled="addConsultantDisable" @click="handleBatchAddConsultant"  >新增顾问</el-button>
          <el-button plain size="mini" @click="toggleSelection()">取消选择</el-button>
      </div>
    </div>


    <div class="table-container">
      <el-table v-loading="listLoading" border ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="55">
        </el-table-column>
        <el-table-column label="项目名称" fixed width="100px">
          <template slot-scope="scope">
            <span class="link-type" @click="handleView(scope.row)">
              {{scope.row.project_name}}<svg-icon icon-class="share-square" />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="公司名称" fixed min-width="100">
          <template slot-scope="scope">
            <span class="link-type" @click="handleViewCompanyDesc(scope.row)">
              {{ scope.row.company_name }}<svg-icon icon-class="share-square" />
            </span>
          </template>
        </el-table-column>
        <el-table-column  label="城市" width="40">
          <template slot-scope="scope">{{ scope.row.city | cityValFilter }}</template>
        </el-table-column>
        <el-table-column label="行业" min-width="80">
          <template slot-scope="scope">{{ scope.row.industry | industryFilter}}</template>
        </el-table-column>
        <el-table-column label="职能" min-width="80">
          <template slot-scope="scope">{{ scope.row.function | jobFilter}}</template>
        </el-table-column>
        <el-table-column label="客户经理" width="75">
          <template slot-scope="scope">{{ getUsernameById(scope.row.client_manager)}}</template>
        </el-table-column>

        <el-table-column label="主要顾问" width="75">
          <template slot-scope="scope">{{ getUsernameById(scope.row.manager_consultant)}}</template>
        </el-table-column>
        <el-table-column  label="状态" width="100">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.project_status | projectStatusFilter}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column  label="推荐" width="60">
          <template slot-scope="scope">
            <span class="link-type" @click="handleViewCv(scope.row)">
              {{ scope.row.cv_count}}<svg-icon icon-class="share-square" />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="180">
          <template slot-scope="scope">
          <span v-if="scope.row.comments && scope.row.comments.length >0" >{{ scope.row.comments[0].comment || ''}}</span>
          <span v-else></span>
          <span v-if="scope.row.comments && scope.row.comments.length >1" class="link-type" @click='handleShowMoreComments(scope.row)'>更多</span>
          <span v-else></span>
          <el-button icon="el-icon-tickets" @click='handleAddComment(scope.row)' size="mini" >新增</el-button>
          </template>
        </el-table-column>
        <el-table-column  label="最近更新" width="100">
          <template slot-scope="scope">{{ scope.row.newest_update_time | timeFromNowFilter }}</template>
        </el-table-column>
        <el-table-column label="级别" width="40">
          <template slot-scope="scope">{{ scope.row.project_priority | projectPriorityFilter }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作"  width="50">
          <template slot-scope="scope">
            <el-dropdown @command="handleCommand" trigger="click">
              <span class="el-dropdown-link">
                <svg-icon icon-class="code" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="(scope.row.project_status !== 'Successful') && (hasRoles(['PROJECT_INFO_MGMT', 'SUPER_ADMIN']) || businessOperable(scope.row) || isAllowMiniRole('CHECK_ALL', scope.row)) " :command='{type:"edit", data: scope.row}' >编辑</el-dropdown-item>
                <el-dropdown-item v-if="checkOperable(scope.row.project_status, 'apply') && isCreateId(scope.row.create_id)" :command='{type:"submit", data: scope.row}' >提交申请</el-dropdown-item>
                <el-dropdown-item v-if="checkOperable(scope.row.project_status, 'cancel') && isCreateId(scope.row.create_id)" :command='{type:"back", data: scope.row}' >撤回申请</el-dropdown-item>
                <el-dropdown-item v-if="checkOperable(scope.row.project_status, 'check') && (hasRoles(['PROJECT_INFO_MGMT', 'SUPER_ADMIN']) || isAllowMiniRole('CHECK_ALL', scope.row)) " :command='{type:"check", data: scope.row}' >审核</el-dropdown-item>
                <el-dropdown-item v-if="checkOperable(scope.row.project_status, 'complete') && (hasRoles(['PROJECT_INFO_MGMT', 'SUPER_ADMIN']) || businessOperable(scope.row) || isAllowMiniRole('CHECK_ALL', scope.row))" :command='{type:"success", data: scope.row}' >成功/关闭</el-dropdown-item>
                <el-dropdown-item v-if="checkOperable(scope.row.project_status, 'stop') && (hasRoles(['PROJECT_INFO_MGMT', 'SUPER_ADMIN']) || businessOperable(scope.row) || isAllowMiniRole('CHECK_ALL', scope.row)) " :command='{type:"stop", data: scope.row}' divided >暂停</el-dropdown-item>
                <el-dropdown-item v-if="checkOperable(scope.row.project_status,  'restart') && (hasRoles(['PROJECT_INFO_MGMT', 'SUPER_ADMIN']) || businessOperable(scope.row) || isAllowMiniRole('CHECK_ALL', scope.row))" :command='{type:"restart", data: scope.row}' >启动</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
      <el-pagination background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current_page" :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.limit" layout="total, sizes, prev, pager, next"
        :total="total"
        >
      </el-pagination>
      </div>
    </div>

    <ProjectDialog :id="dialog_id" :visible="dialog_visible" :status="dialog_status" @closeDialog="handleCloseDialog"> </ProjectDialog>
    <el-tooltip placement="top" content="tooltip">
      <back-to-top transitionName="fade" :customStyle="myBackToTopStyle" :visibilityHeight="300" :backPosition="50"></back-to-top>
    </el-tooltip>

    <el-dialog title="完成" :visible.sync="dialogCompleteVisible" >
      <el-form  :rules="complete_rules" ref="completeForm" :model="complete_temp" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
         <el-form-item label="项目">
          <span>
            {{this.selected_project_title}}
          </span>
        </el-form-item>
        <el-form-item label="项目完成备注" prop="remark" >
          <el-input type="textarea" :rows="4" size="small" v-model="complete_temp.remark" style="width: 280px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCompleteVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="completeProject()">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="撤回申请" :visible.sync="dialogBackVisible" >
      <el-form  :rules="back_rules" ref="backForm" :model="back_temp" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="项目">
          <span>
            {{this.selected_project_title}}
          </span>
        </el-form-item>
        <el-form-item label="撤回备注" prop="remark" >
          <el-input type="textarea" :rows="4" size="small" v-model="back_temp.remark" style="width: 280px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBackVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="back()">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="重新启动项目" :visible.sync="dialogRestartVisible" >
      <el-form  :rules="restart_rules" ref="restartForm" :model="restart_temp" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
         <el-form-item label="项目">
          <span>
            {{this.selected_project_title}}
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remark" >
          <el-input type="textarea" :rows="4" size="small" v-model="restart_temp.remark" style="width: 280px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRestartVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="restartProject">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="暂停项目" :visible.sync="dialogStopVisible" >
      <el-form  :rules="stop_rules" ref="stopForm" :model="stop_temp" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="项目">
          <span>
            {{this.selected_project_title}}
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remark" >
          <el-input type="textarea" :rows="4" size="small" v-model="stop_temp.remark" style="width: 280px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogStopVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="stopProject()">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="审批" :visible.sync="dialogCheckVisible" append-to-body>
      <el-form :rules="check_rules" ref="checkForm" :model="check_temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="项目">
          <span>
            {{this.selected_project_title}}
          </span>
        </el-form-item>
        <el-form-item label="是否同意" required error="必须选择是否同意" prop="status">
          <el-radio v-model="check_temp.status" label="approved">同意</el-radio>
          <el-radio v-model="check_temp.status" label="no_pass">拒绝</el-radio>
        </el-form-item>
        <el-form-item label="备注" >
          <el-input type="textarea" v-model="check_temp.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCheckVisible = false">取 消</el-button>
        <el-button type="primary" @click="check()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="维护客户经理" :visible.sync="updateClientManagerDialogVisible" append-to-body>
      <el-form  :rules="client_manager_rules" ref="clientManagerForm" :model="client_manager_temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="项目">
          <div v-for="item in project_group_for_client_manager" :key="item">
            {{item}}
          </div>
        </el-form-item>
        <el-form-item label="客户经理" prop="client_manager">
          <el-select
          v-model="client_manager_temp.client_manager"
          filterable
          clearable
          collapse-tags
          placeholder="请选择">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateClientManagerDialogVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="updateClientManager">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
    <el-dialog title="维护主要顾问" :visible.sync="updateManagerConsultantDialogVisible" append-to-body>
      <el-form  :rules="manager_consultant_rules" ref="managerConsultantForm" :model="manager_consultant_temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="项目">
          <div v-for="item in project_group_for_manager_consultant" :key="item">
            {{item}}
          </div>
        </el-form-item>
        <el-form-item label="主要顾问" prop="manager_consultant">
          <el-select
          v-model="manager_consultant_temp.manager_consultant"
          filterable
          clearable
          collapse-tags
          placeholder="请选择">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateManagerConsultantDialogVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="updateManagerConsultant">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增顾问" :visible.sync="addConsultantDialogVisible" append-to-body>
      <el-form  :rules="consultant_rules" ref="consultantForm" :model="consultant_temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="项目">
          <div v-for="item in project_group_for_consultant" :key="item" >
            {{item}}
          </div>
        </el-form-item>
        <el-form-item label="顾问" prop="consultant">
          <el-select
          v-model="consultant_temp.consultant"
          filterable
          clearable
          collapse-tags
          placeholder="请选择">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addConsultantDialogVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="addConsultant">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
    <el-dialog title="历史备注" :visible.sync="dialogHistoryCommentsVisible" append-to-body>
      <el-table :data="this.history_comments" border fit highlight-current-row style="width: 100%" >
        <el-table-column  label="备注" width="500px">
          <template slot-scope="comment_scope">
            {{comment_scope.row.comment}}
          </template>
        </el-table-column>
        <el-table-column label="时间" width="100px">
          <template slot-scope="comment_scope">
            {{comment_scope.row.comment_date | timeFilter('{y}-{m}-{d} {h}:{i}') }}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
      <el-pagination background
        @size-change="handleHistoryCommentsSizeChange"
        @current-change="handleHistoryCommentsCurrentChange"
        :current-page="history_comments_current_page" :page-sizes="[10,20,30, 50]"
        :page-size="historyCommentsListQuery.limit" layout="total, sizes, prev, pager, next"
        :total="historyCommentstotal"
        >
      </el-pagination>
      </div>
    </el-dialog>
    <el-dialog title="新增备注" :visible.sync="commentDialogVisible" append-to-body>
      <el-form  :rules="comment_rules" ref="commentForm" :model="comment_temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="备注" prop="comment">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="comment_temp.comment"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="commentDialogVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="addComment">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import API from '@/utils/backend_api'
import Static_Data from '@/data/index'
import BackToTop from '@/components/BackToTop'
import ProjectDialog from '@/views/project/components/projectDialog'
import checkPermission from '@/utils/permission'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
const simulateAsyncOperation = fn => {
  setTimeout(fn, 200)
}
const cityCascaderOptions = Static_Data.city.map((item) => {
  const item_children = []
  if (item.children && item.children.length > 0) {
    item.children.map(function(subitem) {
      item_children.push({ value: subitem.id, label: subitem.label })
    })
  }
  return { value: item.id, label: item.label, children: item_children }
})
export default {
  name: 'project',
  components: { Treeselect, BackToTop, ProjectDialog },
  data() {
    return {
      valueConsistsOf: 'ALL',
      current_user_id: this.$store.getters.userId,
      current_user_roles: this.$store.getters.roles,
      current_users_group: this.$store.getters.usersList,
      MiniRole: Static_Data.mini_roles,
      userOptions: this.$store.getters.usersList.map(item => ({ value: item.id, label: item.username + '(' + item.uid + ')' })),
      selected_project_title: '',
      dialogRestartVisible: false,
      restart_rules: {
        remark: [
          { required: true, message: '必须填写', trigger: 'change' }
        ]
      },
      restart_temp: { id: '', remark: '' },
      dialogStopVisible: false,
      stop_rules: {
        remark: [
          { required: true, message: '必须填写', trigger: 'change' }
        ]
      },
      stop_temp: { id: '', remark: '' },
      addConsultantDisable: true,
      addConsultantDialogVisible: false,
      consultant_rules: {
        consultant: [
          { required: true, message: '必须填写', trigger: 'change' }
        ]
      },
      consultant_temp: { consultant: '', project_id: [] },
      project_group_for_consultant: [],
      updateManagerConsultantDisable: true,
      updateManagerConsultantDialogVisible: false,
      manager_consultant_rules: {
        manager_consultant: [
          { required: true, message: '必须填写', trigger: 'change' }
        ]
      },
      manager_consultant_temp: { manager_consultant: '', project_id: [] },
      project_group_for_manager_consultant: [],
      updateClientManagerDisable: true,
      updateClientManagerDialogVisible: false,
      client_manager_rules: {
        client_manager: [
          { required: true, message: '必须填写', trigger: 'change' }
        ]
      },
      client_manager_temp: { client_manager: '', project_id: [] },
      project_group_for_client_manager: [],
      projectPriorityOptions: Static_Data.project_priority,
      projectStatusOptions: Static_Data.project_status,
      commentDialogVisible: false,
      dialogHistoryCommentsVisible: false,
      comment_rules: {
        comment: [
          { required: true, message: '必须填写', trigger: 'change' }
        ]
      },
      comment_temp: { comment: '' },
      history_comments: [],
      history_comments_current_page: 1,
      historyCommentstotal: 0,
      historyCommentsListQuery: {
        page: 1,
        offset: 0,
        limit: 10,
        project_id: ''
      },
      check_temp: {
        id: '',
        status: 'approved',
        remark: ''
      },
      back_temp: {
        id: '',
        remark: ''
      },
      complete_temp: {
        id: '',
        remark: ''
      },
      complete_rules: {},
      check_rules: {},
      back_rules: {
        remark: [
          { required: true, message: '必须填写理由', trigger: 'change' }
        ]
      },
      dialogCompleteVisible: false,
      dialogCheckVisible: false,
      dialogBackVisible: false,
      allUserOptions: this.$store.getters.usersList,
      dialog_id: '',
      dialog_visible: false,
      dialog_status: '',
      listQuery: {
        page: 1,
        offset: 0,
        limit: 20,
        sort: '-CAST(newest_update_time AS SIGNED)',
        client_manager: '',
        project_name: '',
        company_name: '',
        project_status: '',
        project_priority: '',
        city: [],
        industry: [],
        function: [],
        manager_consultant: ''
      },
      isAllKeyword: false,
      myBackToTopStyle: {
        right: '50px',
        bottom: '25px',
        width: '40px',
        height: '40px',
        'border-radius': '4px',
        'line-height': '45px', // 请保持与高度一致以垂直居中 Please keep consistent with height to center vertically
        background: '#e7eaf1'// 按钮的背景颜色 The background color of the button
      },
      total: 0,
      current_page: 1,
      education_backgroud_options: Static_Data.education_backgroud,
      language_level_options: Static_Data.language_level,
      city_options: Static_Data.city,
      city_cascader_options: cityCascaderOptions,
      industry_options: Static_Data.industry,
      job_options: Static_Data.job,
      company_category_options: Static_Data.company_type,
      userGenderOptions: Static_Data.gender,
      listLoading: true,
      tableData: [],
      multipleSelection: [],
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑人才',
        create: '新增人才'
      }
    }
  },
  created() {
    this.getList()
  },
  filters: {
  },
  computed: {

  },
  methods: {
    authMiniRole(miniRolekey, dept, office) {
      const isHasMiniRoleOffice = this.current_user_roles.some(my_role => my_role === (miniRolekey + '_' + this.MiniRole.MINI_P_OFFICE + '_' + office)) ||
        this.current_user_roles.some(my_role => my_role === (miniRolekey + '_' + this.MiniRole.MINI_P_OFFICE + '_ALL'))
      const isHasMiniRoleDept = this.current_user_roles.some(my_role => my_role === (miniRolekey + '_' + this.MiniRole.MINI_P_DEPT + '_' + dept)) ||
        this.current_user_roles.some(my_role => my_role === (miniRolekey + '_' + this.MiniRole.MINI_P_DEPT + '_ALL'))
      console.log('authMiniRole:', miniRolekey, isHasMiniRoleOffice, isHasMiniRoleDept, (isHasMiniRoleOffice && isHasMiniRoleDept))
      return (isHasMiniRoleOffice && isHasMiniRoleDept)
    },
    isAllowMiniRole(key, data) {
      if (data.create_id && data.create_id !== '') {
        let own_user = {}
        this.current_users_group.map(current_item => {
          if (current_item.id === data.create_id) {
            own_user = current_item
          }
        })
        // console.log('own_user:', own_user)
        return this.authMiniRole(key, own_user.department_id, own_user.office)
      }
      return false
    },
    businessOperable(data) {
      return data.business_roles && data.business_roles.some((item) => (item === 'bd' || item === 'client_manager'))
    },
    hasRoles(roles) {
      return this.current_user_roles.some(item => roles.indexOf(item) >= 0)
    },
    isCreateId(create_id) {
      return create_id === this.current_user_id
    },
    checkOperable(status, action) {
      if (status && action) {
        let action_group = []
        Static_Data.project_status.map(item => {
          if (item.key === status) {
            action_group = item.actions
          }
        })
        if (action_group.indexOf(action) < 0) {
          return false
        }
        return true
      } else {
        return false
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.updateClientManagerDisable = false
        this.updateManagerConsultantDisable = false
        this.addConsultantDisable = false
      } else {
        this.updateClientManagerDisable = true
        this.updateManagerConsultantDisable = true
        this.addConsultantDisable = true
      }
    },
    handleBatchAddConsultant() {
      this.consultant_temp = { consultant: '', project_id: [] }
      this.project_group_for_consultant = []
      this.multipleSelection.map(item => {
        this.consultant_temp.project_id.push(item.id)
        this.project_group_for_consultant.push(item.project_name + '(' + item.company_name + ')')
      })
      this.addConsultantDialogVisible = true
      this.$nextTick(() => {
        this.$refs['consultantForm'].clearValidate()
      })
    },
    handleBatchUpdateManagerConsultant() {
      this.manager_consultant_temp = { manager_consultant: '', project_id: [] }
      this.project_group_for_manager_consultant = []
      this.multipleSelection.map(item => {
        this.manager_consultant_temp.project_id.push(item.id)
        this.project_group_for_manager_consultant.push(item.project_name + '(' + item.company_name + ')')
      })
      this.updateManagerConsultantDialogVisible = true
      this.$nextTick(() => {
        this.$refs['managerConsultantForm'].clearValidate()
      })
    },
    handleBatchUpdateClientManager() {
      this.client_manager_temp = { client_manager: '', project_id: [] }
      this.project_group_for_client_manager = []
      this.multipleSelection.map(item => {
        this.client_manager_temp.project_id.push(item.id)
        this.project_group_for_client_manager.push(item.project_name + '(' + item.company_name + ')')
      })
      this.updateClientManagerDialogVisible = true
      this.$nextTick(() => {
        this.$refs['clientManagerForm'].clearValidate()
      })
    },
    addConsultant() {
      this.$refs['consultantForm'].validate((valid) => {
        if (valid) {
          API.project.addConsultant(this.consultant_temp).then((response) => {
            // console.log(response)
            // for (const k of response.data) {
            //   for (const v of this.tableData) {
            //     if (v.id === k.id) {
            //       const index = this.tableData.indexOf(v)
            //       this.tableData.splice(index, 1, k)
            //       break
            //     }
            //   }
            // }
            this.$message({
              type: 'success',
              message: '添加成功成功!'
            })
            this.addConsultantDialogVisible = false
            this.consultant_temp = { consultant: '', project_id: [] }
            this.project_group_for_consultant = []
          })
        }
      })
    },
    updateManagerConsultant() {
      this.$refs['managerConsultantForm'].validate((valid) => {
        if (valid) {
          API.project.updateManagerConsultant(this.manager_consultant_temp).then((response) => {
            console.log(response)
            for (const k of response.data) {
              for (const v of this.tableData) {
                if (v.id === k.id) {
                  const index = this.tableData.indexOf(v)
                  this.tableData.splice(index, 1, k)
                  break
                }
              }
            }
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.updateManagerConsultantDialogVisible = false
            this.manager_consultant_temp = { manager_consultant: '', project_id: [] }
            this.project_group_for_manager_consultant = []
          })
        }
      })
    },
    updateClientManager() {
      this.$refs['clientManagerForm'].validate((valid) => {
        if (valid) {
          API.project.updateClientManager(this.client_manager_temp).then((response) => {
            console.log(response)
            for (const k of response.data) {
              for (const v of this.tableData) {
                if (v.id === k.id) {
                  const index = this.tableData.indexOf(v)
                  this.tableData.splice(index, 1, k)
                  break
                }
              }
            }
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.updateClientManagerDialogVisible = false
            this.client_manager_temp = { client_manager: '', project_id: [] }
            this.project_group_for_client_manager = []
          })
        }
      })
    },
    checkPermission,
    handleAddComment(data) {
      this.comment_temp = { project_id: data.id, comment: '' }
      this.commentDialogVisible = true
      this.$nextTick(() => {
        this.$refs['commentForm'].clearValidate()
      })
    },
    addComment() {
      this.$refs['commentForm'].validate((valid) => {
        if (valid) {
          API.project.add_comment(this.comment_temp).then((response) => {
            for (const v of this.tableData) {
              if (v.id === this.comment_temp.project_id) {
                const index = this.tableData.indexOf(v)
                this.tableData.splice(index, 1, response.data)
                break
              }
            }
            this.commentDialogVisible = false
            this.comment_temp = { comment: '' }
          })
        }
      })
    },
    handleShowMoreComments(data) {
      this.historyCommentsListQuery.project_id = data.id
      this.getHistoryCommentsList(this.historyCommentsListQuery)
      this.dialogHistoryCommentsVisible = true
    },
    getHistoryCommentsList(query) {
      if (query && query.project_id) {
        API.project.comments(query).then(response => {
          this.history_comments = response.data
          if (response.headers && response.headers['x-total-count']) {
            this.historyCommentstotal = Number(response.headers['x-total-count'])
          }
        })
      } else {
        this.$message({
          showClose: true,
          message: '请先选择项目',
          type: 'warning'
        })
      }
    },
    handleHistoryCommentsSizeChange(val) {
      this.historyCommentsListQuery.limit = val
      this.getHistoryCommentsList(this.historyCommentsListQuery)
    },
    handleHistoryCommentsCurrentChange(val) {
      if (val >= 1) {
        this.history_comments_current_page = val
        this.historyCommentsListQuery.offset = (val - 1) * this.historyCommentsListQuery.limit
        this.getHistoryCommentsList(this.historyCommentsListQuery)
      }
    },
    getUsernameById(id) {
      let username = ''
      this.allUserOptions.map(item => {
        if (item.id === id) {
          username = item.username
        }
      })
      return username
    },
    handleCommand(val) {
      this.selected_project_title = val.data.project_name + '(' + val.data.company_name + ')'
      if (val.type && val.data && val.type === 'view') {
        this.handleView(val.data)
      }
      if (val.type && val.data && val.type === 'edit') {
        this.handleUpdate(val.data)
      }
      if (val.type && val.data && val.type === 'submit') {
        this.handleSubmit(val.data)
      }
      if (val.type && val.data && val.type === 'back') {
        this.handleBack(val.data)
      }
      if (val.type && val.data && val.type === 'check') {
        this.handleCheck(val.data)
      }
      if (val.type && val.data && val.type === 'success') {
        this.handleComplete(val.data)
      }
      if (val.type && val.data && val.type === 'restart') {
        this.handleRestart(val.data)
      }
      if (val.type && val.data && val.type === 'stop') {
        this.handleStop(val.data)
      }
    },
    handleViewCompanyDesc(row) {
      /* 验证是否存在查看权限 */
      if (row && row.company_id) {
        this.$router.push({
          name: 'companyDetail',
          params: {
            id: row.company_id,
            name: row.company_name,
            tab: 'base'
          }
        })
      }
    },
    handleViewCv(row) {
      /* 验证是否存在查看权限 */
      this.$router.push({
        name: 'projectDetail',
        params: {
          id: row.id,
          name: row.project_name,
          tab: 'cv'
        }
      })
    },
    handleFilter() {
      this.getList()
    },
    clearOptions() {
      this.listQuery = {
        page: 1,
        offset: 0,
        limit: 20,
        sort: '-CAST(newest_update_time AS SIGNED)',
        client_manager: '',
        project_name: '',
        company_name: '',
        project_status: '',
        project_priority: '',
        city: [],
        industry: [],
        function: [],
        manager_consultant: ''
      }
    },
    getList() {
      this.listLoading = true
      console.log('api user query:')
      console.log(this.listQuery)
      API.project.all(this.listQuery).then(response => {
        this.tableData = response.data
        if (response.headers && response.headers['x-total-count']) {
          this.total = Number(response.headers['x-total-count'])
        }
        this.listLoading = false
      })
    },
    handleView(row) {
      if ((row.business_roles && row.business_roles.length > 0) || this.hasRoles(['PROJECT_INFO_MGMT', 'SUPER_ADMIN']) || this.isAllowMiniRole('CHECK_ALL', row)) {
        this.$router.push({
          name: 'projectDetail',
          params: {
            id: row.id,
            name: row.project_name,
            tab: 'base'
          }
        })
      } else {
        this.$message({
          showClose: true,
          message: '请先申请成为项目组成员'
        })
      }
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      if (val >= 1) {
        this.current_page = val
        this.listQuery.offset = (val - 1) * this.listQuery.limit
        this.getList()
      }
    },

    handleCloseDialog(val) {
      console.log(' handleClosedialog ...')
      console.log(val)
      this.dialog_visible = false
      this.dialog_id = ''
      if (val && val.type === 'create_success' && val.data) {
        this.tableData.unshift(val.data)
      }
      if (val && val.type === 'submit_success' && val.data) {
        for (const v of this.tableData) {
          if (v.id === val.data.id) {
            const index = this.tableData.indexOf(v)
            this.tableData.splice(index, 1, val.data)
            break
          }
        }
      }
      if (val && val.type === 'update_success' && val.data) {
        for (const v of this.tableData) {
          if (v.id === val.data.id) {
            const index = this.tableData.indexOf(v)
            this.tableData.splice(index, 1, val.data)
            break
          }
        }
      }
    },
    back() {
      this.$refs['backForm'].validate((valid) => {
        if (valid) {
          API.project.back(this.back_temp.id, this.back_temp).then(response => {
            for (const v of this.tableData) {
              if (v.id === this.back_temp.id) {
                const index = this.tableData.indexOf(v)
                this.tableData.splice(index, 1, response.data)
                break
              }
            }
            this.resetTemp()
            this.$message({
              type: 'success',
              message: '撤回成功!'
            })
            this.dialogBackVisible = false
          })
        }
      })
    },
    restartProject() {
      this.$refs['restartForm'].validate((valid) => {
        if (valid) {
          API.project.restart(this.restart_temp.id, this.restart_temp).then(response => {
            for (const v of this.tableData) {
              if (v.id === this.restart_temp.id) {
                const index = this.tableData.indexOf(v)
                this.tableData.splice(index, 1, response.data)
                break
              }
            }
            this.$message({
              type: 'success',
              message: '启动成功!'
            })
            this.dialogRestartVisible = false
          })
        }
      })
    },
    stopProject() {
      this.$refs['stopForm'].validate((valid) => {
        if (valid) {
          API.project.stop(this.stop_temp.id, this.stop_temp).then(response => {
            for (const v of this.tableData) {
              if (v.id === this.stop_temp.id) {
                const index = this.tableData.indexOf(v)
                this.tableData.splice(index, 1, response.data)
                break
              }
            }
            this.$message({
              type: 'success',
              message: '暂停成功!'
            })
            this.dialogStopVisible = false
          })
        }
      })
    },
    resetTemp() {
      this.temp = {}
    },
    check() {
      this.$refs['checkForm'].validate((valid) => {
        if (valid) {
          if (this.check_temp.status === 'approved') {
            API.project.pass(this.check_temp.id, this.check_temp).then(response => {
              for (const v of this.tableData) {
                if (v.id === this.check_temp.id) {
                  const index = this.tableData.indexOf(v)
                  this.tableData.splice(index, 1, response.data)
                  break
                }
              }
              this.resetTemp()
              this.$message({
                type: 'success',
                message: '成功!'
              })
              this.dialogCheckVisible = false
            })
          }
          if (this.check_temp.status === 'no_pass') {
            API.project.no_pass(this.check_temp.id, this.check_temp).then(response => {
              for (const v of this.tableData) {
                if (v.id === this.check_temp.id) {
                  const index = this.tableData.indexOf(v)
                  this.tableData.splice(index, 1, response.data)
                  break
                }
              }
              this.resetTemp()
              this.$message({
                type: 'success',
                message: '打回成功!'
              })
              this.dialogCheckVisible = false
            })
          }
        }
      })
    },
    handleCreate() {
      this.dialog_id = ''
      this.dialog_visible = true
      this.dialog_status = 'create'
    },
    handleComplete(row) {
      if (row && row.id) {
        this.complete_temp = { id: row.id, remark: '' }
        this.dialogCompleteVisible = true
      }
      this.$nextTick(() => {
        this.$refs['completeForm'].clearValidate()
      })
    },
    handleRestart(row) {
      if (row && row.id) {
        this.restart_temp = { id: row.id, remark: '' }
        this.dialogRestartVisible = true
      }
      this.$nextTick(() => {
        this.$refs['restartForm'].clearValidate()
      })
    },
    handleStop(row) {
      if (row && row.id) {
        this.stop_temp = { id: row.id, remark: '' }
        this.dialogStopVisible = true
      }
      this.$nextTick(() => {
        this.$refs['stopForm'].clearValidate()
      })
    },
    completeProject() {
      this.$refs['completeForm'].validate((valid) => {
        if (valid) {
          API.project.complete(this.complete_temp.id, this.complete_temp).then(response => {
            for (const v of this.tableData) {
              if (v.id === this.complete_temp.id) {
                const index = this.tableData.indexOf(v)
                this.tableData.splice(index, 1, response.data)
                break
              }
            }
            this.resetTemp()
            this.$message({
              type: 'success',
              message: '成功!'
            })
            this.dialogCompleteVisible = false
          })
        }
      })
    },
    handleBack(row) {
      if (row && row.id) {
        this.back_temp = { id: row.id, remark: '' }
        this.dialogBackVisible = true
      }
      this.$nextTick(() => {
        this.$refs['backForm'].clearValidate()
      })
    },
    handleCheck(row) {
      if (row && row.id) {
        this.check_temp = { id: row.id, status: 'approved', remark: '' }
        this.dialogCheckVisible = true
      }
      this.$nextTick(() => {
        this.$refs['checkForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      if (row && row.id) {
        this.dialog_id = row.id
        this.dialog_visible = true
        this.dialog_status = 'update'
      }
    },
    handleSubmit(row) {
      if (row && row.id) {
        this.dialog_id = row.id
        this.dialog_visible = true
        this.dialog_status = 'submit'
      }
    },
    loadChildrenOptions({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        switch (parentNode.id) {
          default: /* empty */
            simulateAsyncOperation(() => {
              callback()
            })
        }
      }
    }
  }
}
</script>
<style scoped>
  .search-container{
    display: block;
    border: 1px solid #ebebeb;
    margin: 2px 2px 2px 2px;
  }
  .search-option-row{
    display: block;
    margin: 6px 0px 6px 6px;
  }
  .search-option-label{
    display: inline-block;
    width: 9%;
    text-align: right;
  }
  .search-option-col1-for-row{
    display: inline-block;
    width:  90%;
  }
  .search-option-col{
    display: inline-block;
    width:  15%;
  }
  .search-button-row{
    display: block;
    margin: 2px 0px 2px 2px;
  }
  .search-button-label{
    display: inline-block;
    width: 8%;
    text-align: right;
  }
  .search-button-col{
    display: inline-block;
    width: 25%;
  }

  .table-header-row {
    display: block;
    border: 1px solid #ebebeb;
    margin: 2px 0px 2px 2px;
  }

  .table-header-button {
    display: inline-block;
    margin: 2px 0px 2px 2px;

  }

  .table-container{
    border: 1px solid #ebebeb;
    margin: 2px 2px 2px 2px;
  }

  .select-item {
    display: inline-block;
    vertical-align: middle;
    width: 200px;
  }

  .form-row {
    display: block;
  }

  .form-item {
    width: 48%
  }

  .form-item-full {
    width: 100%
  }
</style>